package com.sunday.pinxinghui.model.main;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseFragment;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.IndexViewPager;
import com.sunday.pinxinghui.MainActivity;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.IndexCategory;
import com.sunday.pinxinghui.entity.Message;
import com.sunday.pinxinghui.entity.Nums;
import com.sunday.pinxinghui.event.LocSucceed;
import com.sunday.pinxinghui.model.MessageListActivity;
import com.sunday.pinxinghui.model.index.IndexClasssifyFragment;
import com.sunday.pinxinghui.model.index.SelectCityListActivity;
import com.sunday.pinxinghui.model.index.TodayFragment;
import com.sunday.pinxinghui.model.index.TodayNewFragment;
import com.sunday.pinxinghui.model.products.SearchProductListActivity;
import com.sunday.pinxinghui.network.ApiClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

/**
 * Created by 刘涛 on 2017/8/3.
 */

public class IndexFragment extends BaseFragment {

    @Bind(R.id.city_name)
    TextView cityName;
    @Bind(R.id.txt_news_num)
    TextView txtNewsNum;
    @Bind(R.id.layout_news)
    FrameLayout layoutNews;
    @Bind(R.id.layout_search)
    LinearLayout layoutSearch;
    @Bind(R.id.tab_layout)
    TabLayout tabLayout;
    @Bind(R.id.appbar_layout)
    AppBarLayout appbarLayout;
    @Bind(R.id.view_pager)
    IndexViewPager viewPager;

    private List<String> titles = new ArrayList<>();
    private List<IndexCategory> productClassifyList = new ArrayList<>();

    public static IndexFragment newInstance() {
        IndexFragment fragment = new IndexFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void setCity(final String city) {
        if (cityName != null) {
            ((MainActivity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //此时已在主线程中，可以更新UI了
                    cityName.setText(city);
                }
            });
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.index_fragment, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        cityName.setText(BaseApplication.getInstance().getCityName());
        getTabTitles();
    }


    private void getTabTitles() {
        //
        titles.clear();
        titles.add("今日特卖");
        showLoadingDialog(0);
        Call<ResultDO<List<IndexCategory>>> call = ApiClient.getApiAdapter().getIndexCategory();
        call.enqueue(new Callback<ResultDO<List<IndexCategory>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<IndexCategory>>> call, Response<ResultDO<List<IndexCategory>>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    for (IndexCategory item : response.body().getResult()) {
                        titles.add(item.getName());
                    }
                    productClassifyList.clear();
                    productClassifyList.addAll(response.body().getResult());
                    initFragments();
                    getNewsNum();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<IndexCategory>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });


    }

    public void getNewsNum() {
        Call<ResultDO<Nums>> call = ApiClient.getApiAdapter().totalMessageCount(BaseApplication.getInstance().getMember().getId());
        call.enqueue(new Callback<ResultDO<Nums>>() {
            @Override
            public void onResponse(Call<ResultDO<Nums>> call, Response<ResultDO<Nums>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    txtNewsNum.setVisibility(response.body().getResult().getNum() == 0 ? View.GONE : View.VISIBLE);
                    txtNewsNum.setText(response.body().getResult().getNum() + "");
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Nums>> call, Throwable t) {
                ;
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });

    }


    private void initFragments() {
        viewPager.setAdapter(new IndexViewPagerAdapter(getChildFragmentManager()));
        viewPager.setOffscreenPageLimit(titles.size());
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setOnCheckCanScrollListener(new IndexViewPager.OnCheckCanScrollListener() {
            @Override
            public boolean isCanScroll() {
                return !checkTabLayoutVisible();
            }
        });

    }

    public void setPage(int catId) {
        int page = 0;
        for (int i = 0; i < productClassifyList.size(); i++) {
            if (catId == productClassifyList.get(i).getId()) {
                page = i + 1;
                break;
            }
        }
        viewPager.setCurrentItem(page, false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public class IndexViewPagerAdapter extends FragmentPagerAdapter {

        private Fragment[] fragments;

        public IndexViewPagerAdapter(FragmentManager fm) {
            super(fm);
            fragments = new Fragment[titles.size()];
        }

        @Override
        public Fragment getItem(int position) {
            if (fragments[position] == null) {
                if (position == 0) {
                    fragments[position] = TodayNewFragment.newInstance();
                } else {
                    fragments[position] = IndexClasssifyFragment.newInstance(productClassifyList.get(position - 1).getId(), titles.get(position));
                }
            }
            return fragments[position];
        }

        @Override
        public int getCount() {
            return titles.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);
        }
    }


    public boolean checkTabLayoutVisible() {
        boolean cover = false;
        Rect rect = new Rect();
        cover = tabLayout.getGlobalVisibleRect(rect);
        if (cover) {
            if (rect.width() >= tabLayout.getMeasuredWidth() && rect.height() >= tabLayout.getMeasuredHeight()) {
                return !cover;
            }
        }
        return true;
    }

    @OnClick(R.id.layout_search)
    void onClick() {
        intent = new Intent(mContext, SearchProductListActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.city_name)
    void selectCity() {
        intent = new Intent(mContext, SelectCityListActivity.class);
        startActivityForResult(intent, 0x111);
    }

    @OnClick(R.id.layout_news)
    void newsNum() {
        intent = new Intent(mContext, MessageListActivity.class);
        startActivity(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        String city = data.getStringExtra("cityName");
        int cityId = data.getIntExtra("cityId", 0);
        cityName.setText(city);
        BaseApplication.getInstance().setCityName(city);
        BaseApplication.getInstance().setCityId(cityId);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            getNewsNum();
        }
    }
}
